package com.newworld.dmsapp2.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.designtask.AssignAndReassignTaskActivity;
import com.newworld.dmsapp2.activity.designtask.SelectServerActivity;
import com.newworld.dmsapp2.bean.InitOperation;
import com.newworld.dmsapp2.bean.InitProgressFunction;
import com.newworld.dmsapp2.bean.InitTaskState;
import com.newworld.dmsapp2.bean.Server;
import com.newworld.dmsapp2.bean.Task;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.fragment.bean.InitPhotoVoiceItemEntity;
import com.newworld.dmsapp2.fragment.bean.InitTextItemEntity;
import com.newworld.dmsapp2.ui.view.CustomButtonItem;
import com.newworld.dmsapp2.ui.view.CustomDialog;
import com.newworld.dmsapp2.ui.view.CustomLoadingDialog;
import com.newworld.dmsapp2.ui.view.CustomPhotoVoiceItem;
import com.newworld.dmsapp2.ui.view.CustomTextItem;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.InitFunctionUtil;
import com.newworld.dmsapp2.util.InitViewUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.StringUtil;
import com.newworld.dmsapp2.util.Tool;

public class SingleDetailActivity extends BaseActivity implements
		OnClickListener {

	private TextView titleCenterTv;
	private LinearLayout leftLinLayout;
	private LinearLayout mainLayout;
	private CustomLoadingDialog uploadingdialog;
	private ProgressBar loginbar;

	private Intent intent;
	private Bundle bundle;
	private String sessionId;
	private User user;
	private Task task;
	private List<InitProgressFunction> initProgressFunctions = new ArrayList<InitProgressFunction>();
	private static InitTaskState initTS = new InitTaskState();
	private static InitProgressFunction initPF = new InitProgressFunction();
	private static List<InitOperation> initOPs = new ArrayList<InitOperation>();
	private static InitOperation initOP = new InitOperation();
	private List<InitTextItemEntity> textItemList = new ArrayList<InitTextItemEntity>();
	private InitPhotoVoiceItemEntity photoVoiceEntity = new InitPhotoVoiceItemEntity();
	private boolean isReporter;
	private String peopleType;
	private String listRealFunctionCode;
	private String operationFunctionCode;
	private String operationName;
	private String message;
	private List<Server> servers;
	private String repairTime;	
	static CustomButtonItem cusbuttonItem;
	private String functionPeopleType,functioncode,houseId;
	private String repairId;
	private Server serverAfter;
	private Server server;
	private String houseFullName;
	

	Handler mHandler = new Handler() {
		@SuppressLint("NewApi")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Bundle b = new Bundle();
			Intent i = new Intent();
			switch (msg.what) {
			case Config.HANDLER_MSG_SUCCESS:
				addViews();
				Toast.makeText(SingleDetailActivity.this, message,
						Toast.LENGTH_SHORT);
				loginbar.setVisibility(View.INVISIBLE);
				/*&&!StringUtil.isStringEqual(initOP.getOperationName(), "确认接单")
				&&!StringUtil.isStringEqual(initOP.getOperationName(), "开始维修")
				&&!StringUtil.isStringEqual(initOP.getOperationName(), "申请改派")*/
				/*if (!functioncode
						.equals(Config.FUNCTION_REAL_GETPMPROGRESSLIST)
					||!StringUtil.isStringEqual(initOP.getOperationName(), "开始维修")
					) {// 项目经理
					getServers();
				}*/
				if (StringUtil.isStringEqual(initOP.getOperationName(), "派单")
						||StringUtil.isStringEqual(initOP.getOperationName(), "改派")
					) {// 只在派单和改派操作时才获取服务人员信息
					getServers();
				}
				loginbar.setVisibility(View.INVISIBLE);
				if(null!=uploadingdialog){
					if (uploadingdialog.isShowing()) {
						uploadingdialog.dismiss();
					} else {
						uploadingdialog.show();
					}
				}
				break;
			case Config.HANDLER_MSG_OPERATION_SUCCESS:
				if(null!=uploadingdialog){
					if (uploadingdialog.isShowing()) {
						uploadingdialog.dismiss();
					} else {
						uploadingdialog.show();
					}
				}
				
				
				if (StringUtil.isStringEqual(initOP.getOperationName(), "确认接单")) {
					if (Tool.isNetworkAvailable(SingleDetailActivity.this)) {
						loginbar.setVisibility(View.VISIBLE);
						mainLayout.removeAllViews();
						new Thread(getDataRun).start();
						/*btn_accept_repair.setBackground(getResources().getDrawable(
								R.drawable.button_blue_press));
						btn_accept_repair.setEnabled(false);
						btn_start_repair.setBackground(getResources().getDrawable(
								R.drawable.button_blue));
						btn_start_repair.setEnabled(true);*/
					} else {
						Toast.makeText(SingleDetailActivity.this, "请设置网络",
								Toast.LENGTH_SHORT).show();

					}
				}else if (StringUtil.isStringEqual(initOP.getOperationName(), "开始维修")) {
					if (Tool.isNetworkAvailable(SingleDetailActivity.this)) {
						saveLocalTask();
						b.putSerializable(Config.INITTASTSTATE, initTS);
						b.putSerializable(Config.INITPROGRESSFUNCTION, initPF);
						b.putSerializable(Config.TASK, task);
						b.putSerializable(Config.ISREPORTER, isReporter);
						b.putString(Config.PEOPLETYPE, peopleType);
						b.putString(Config.HOUSEFULLNAME,houseFullName);
						
						b.putString(Config.FUNCTIONCODE, listRealFunctionCode);
						i = new Intent(SingleDetailActivity.this,
								DoubleDetailActivity.class);
						i.putExtras(b);
						startActivity(i);
						finish();
					} else {
						Toast.makeText(SingleDetailActivity.this, "请设置网络",
								Toast.LENGTH_SHORT).show();

					}
				} else {
					finish();
				}

				Toast.makeText(SingleDetailActivity.this, message,
						Toast.LENGTH_SHORT);
				break;
			case Config.HANDLER_MSG_GETSEVER_SUCCESS:
				loginbar.setVisibility(View.INVISIBLE);
				if(null!=uploadingdialog){
					if (uploadingdialog.isShowing()) {
						uploadingdialog.dismiss();
					} else {
						uploadingdialog.show();
					}
				}
				if(null != servers){
					System.out.println("servers.size()+" + servers.size());
					
					if (initTS.getTaskState().contains(Config.TASKSTATE_NOTDISTRIBUTE)) {//待分配
						for (Server s : servers) {
							if (s.isSelected()) {
								server = s;
							}
						}
					} else {
						for (Server s : servers) {
							Log.e("选择人员", "s>>>"+s.getUserId());
							Log.e("选择人员", "getDepartDispatcher_id>>>"+task.getDepartDispatcher_id());
							Log.e("选择人员", "getServer_id>>>"+task.getServer_id());
							if (null != task.getDepartDispatcher_id() && task.getDepartDispatcher_id().equals(
									s.getUserId())) {
								server = s;
								serverAfter = server;
							}else if(null != task.getServer_id() && task.getServer_id().equals(
											s.getUserId())) {
								server = s;
								serverAfter = server;
							}
						}
					}
				}
				
				break;
			case Config.HANDLER_MSG_FAIL:
				if(null!= uploadingdialog){
					if (uploadingdialog.isShowing()) {
						uploadingdialog.dismiss();
					} else {
						uploadingdialog.show();
					}
				}
				
				loginbar.setVisibility(android.view.View.INVISIBLE);
				Toast.makeText(SingleDetailActivity.this, message,
						Toast.LENGTH_SHORT);
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_single_detail);
		initData();
		initViews();
		initEvents();

		if (Tool.isNetworkAvailable(SingleDetailActivity.this)) {
			loginbar.setVisibility(View.VISIBLE);
			new Thread(getDataRun).start();
		} else {
			Toast.makeText(this, "请设置网络", Toast.LENGTH_SHORT).show();

		}
	}

	private void initData() {
		intent = getIntent();
		bundle = intent.getExtras();
		user = SingleSample.getInstance(this).getUser();
		initPF = (InitProgressFunction) bundle
				.getSerializable(Config.INITPROGRESSFUNCTION);
		functioncode = initPF.getProgressFunction();
		houseFullName = bundle.getString(Config.HOUSEFULLNAME);
		houseId = bundle.getString(Config.HOUSEID);
		Log.e("initPF",initPF+"");
		task = (Task) bundle.getSerializable(Config.TASK);
		repairId = task.getRepairId();
		if (null != user) {
			if (null != user.getSessionId() && !user.getSessionId().equals("")) {
				sessionId = user.getSessionId();
			}
		}
		if(user.isTaskExistByRepairId(repairId)){//本地有保存
			task = user.getTasksByRepairId(repairId).get(0);
			if(task.isStopflag()){//停止维修
				initTS = (InitTaskState) bundle.getSerializable(Config.INITTASTSTATE);
			}else{//维修中
				initTS = Tool.getInitTaskStateByCode(initPF, "serving");
			}
		}
		initTS = (InitTaskState) bundle.getSerializable(Config.INITTASTSTATE);
		//Log.e("initTS-->",(initTS.getOperation().get(0)).getSegue().toString());
		initOPs = Tool.getInitOperationOfPage(initTS, 1);
		isReporter = bundle.getBoolean(Config.ISREPORTER);
		peopleType = bundle.getString(Config.PEOPLETYPE);
		listRealFunctionCode = bundle.getString(Config.FUNCTIONCODE);
		InitFunctionUtil functionUtil = new InitFunctionUtil(this);
		initProgressFunctions = functionUtil.getProgressFunction();
		textItemList = InitViewUtil.getSingleTextItemContent(task, initTS);
	}

	@Override
	protected void initViews() {
		// TODO Auto-generated method stub
		titleCenterTv = (TextView) findViewById(R.id.titlebar_left_center_title);
		leftLinLayout = (LinearLayout) findViewById(R.id.titlebar_left_left_layout);
		mainLayout = (LinearLayout) findViewById(R.id.single_detail_ly);
		loginbar = (ProgressBar) findViewById(R.id.single_detail_progressBar);
	}

	/**
	 * 动态布局
	 */
	private void addViews() {

		LinearLayout.LayoutParams LP_FW = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		// 文本信息显示
		for (InitTextItemEntity te : textItemList) {
			CustomTextItem cutextItem = new CustomTextItem(this);
			LinearLayout textItem = cutextItem.getCustomTextItem(this, te,
					task, 0);
			mainLayout.addView(textItem, LP_FW);
		}

		// 图片 、录音显示
		photoVoiceEntity.setImagePath1(task.getProblemImage1());
		photoVoiceEntity.setImagePath2(task.getProblemImage2());
		photoVoiceEntity.setVoicePath(task.getProblemVoice());
		Log.e("task图片录音附件","1"+task.getProblemImage1()+"2"+task.getProblemImage2()+"3"+task.getProblemVoice());
		//photoVoiceEntity.setVoiceTime(task.getProblenmVoiceTime());
		photoVoiceEntity.setChangeView(false);// 不可编辑图片、录音
		CustomPhotoVoiceItem cuPhotoVoiceItem = new CustomPhotoVoiceItem(this);
		LinearLayout photoVoiceItem = cuPhotoVoiceItem.getCustomPhotoVoiceItem(
				this, photoVoiceEntity,false);
		mainLayout.addView(photoVoiceItem, LP_FW);

		// 按钮显示
		cusbuttonItem = new CustomButtonItem(this);
		LinearLayout buttonItem;
		if(initTS.getStatusType_typeCode().equals(Config.TYPECODE_RECEIVEORDER)){
			buttonItem = cusbuttonItem.getCustomButtonItem(this,
					initOPs,true);
		}else{
			buttonItem = cusbuttonItem.getCustomButtonItem(this,
					initOPs,false);
		}
		
		mainLayout.addView(buttonItem, LP_FW);
		if (null != initOPs) {
			switch (initOPs.size()) {
			case 1:
				cusbuttonItem.setButtonOnClick(btnListener0);
				break;
			case 2:
				cusbuttonItem.setButtonOnClick(btnListener0, btnListener1);
				break;
			case 3:
				cusbuttonItem.setButtonOnClick(btnListener0, btnListener1,
						btnListener2);
				break;
			default:
				break;
			}

		}

	}

	OnClickListener btnListener0 = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			btnClickEvent(0);
		}
	};

	OnClickListener btnListener1 = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			btnClickEvent(1);
		}
	};

	OnClickListener btnListener2 = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			btnClickEvent(2);
		}
	};

	private void btnClickEvent(int position) {
		initOP = initOPs.get(position);
		operationFunctionCode = initOP.getFunctionCode();
		operationName = initOP.getOperationName();
		String op = operationFunctionCode + operationName;
		Log.e("op",op+"'");
		Bundle b = new Bundle();
		Intent i = new Intent();
		Toast.makeText(SingleDetailActivity.this, operationName,
				Toast.LENGTH_SHORT).show();
		if (operationName.contains("分配")
				|| (operationName.contains("派") && !operationName
						.equals("申请改派"))) {// 各种派单、改派操作
			b.putSerializable(Config.TASK, task);
			b.putSerializable(Config.PEOPLETYPE, peopleType);
			b.putSerializable(Config.INITOPERATION, initOP);
			
			b.putString(Config.REPAIRID, repairId);
			b.putString(Config.HOUSEID, task.getHouse_id());
			b.putString(Config.PEOPLETYPE, peopleType);
			b.putString(Config.TASKSTATE, task.getTaskState());
			b.putSerializable(Config.SERVERLIST,(Serializable) servers);
			
			i = new Intent(SingleDetailActivity.this,
					SelectServerActivity.class);
			i.putExtras(b);
			startActivityForResult(i, 0);
			finish();
		}else if (StringUtil.isStringEqual(initOP.getOperationName(),
						"继续维修")) {
			if (Tool.isNetworkAvailable(SingleDetailActivity.this)) {
				saveLocalTask();
				b.putSerializable(Config.INITTASTSTATE, initTS);
				b.putSerializable(Config.INITPROGRESSFUNCTION, initPF);
				b.putSerializable(Config.TASK, task);
				b.putSerializable(Config.ISREPORTER, isReporter);
				b.putString(Config.PEOPLETYPE, peopleType);
				b.putString(Config.HOUSEFULLNAME, houseFullName);
				
				b.putString(Config.FUNCTIONCODE, listRealFunctionCode);
				i = new Intent(SingleDetailActivity.this,
						DoubleDetailActivity.class);
				i.putExtras(b);
				startActivity(i);
				finish();
			} else {
				Toast.makeText(SingleDetailActivity.this, "请设置网络",
						Toast.LENGTH_SHORT).show();

			}
		} else {// 直接与服务器交互的操作
				// 标准的对话框封装
			final CustomDialog dialog2 = new CustomDialog(
					SingleDetailActivity.this);

			dialog2.setTitle(operationName);
			dialog2.setDetial("是否要" + operationName + "？");
			dialog2.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog2.dismiss();
				}
			});
			dialog2.show();
			dialog2.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog2.dismiss();
					uploadingdialog = new CustomLoadingDialog(
							SingleDetailActivity.this, operationName + "...");
					if (uploadingdialog.isShowing()) {
						uploadingdialog.dismiss();
					} else {
						uploadingdialog.show();
					}
					if (Tool.isNetworkAvailable(SingleDetailActivity.this)) {
						loginbar.setVisibility(View.VISIBLE);
						new Thread(postOperationRun).start();
					} else {
						Toast.makeText(SingleDetailActivity.this, "请设置网络",
								Toast.LENGTH_SHORT).show();

					}

				}
			});
			dialog2.show();
		}

	}

	@Override
	protected void initEvents() {
		// TODO Auto-generated method stub
		titleCenterTv.setText("单节点界面");
		leftLinLayout.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.titlebar_left_left_layout:
			// TODO Auto-generated method stub
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键

			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	// 请求服务人员列表
		private void getServers() {
			if (Tool.isNetworkAvailable(SingleDetailActivity.this)) {
				try {

					User u;
					String result = null;
					String url = null;
					Map<String, String> map = new HashMap<String, String>();
					//System.out.println("houseId--------->" + task.getHouse_id());
					System.out.println("houseId--------->" + houseId);
					if (functioncode
							.equals(Config.FUNCTION_REAL_GETDISPATCHTASKLIST)
							|| functioncode
									.equals(Config.FUNCTION_REAL_GETREDISPATCHTASKLIST)
							|| functioncode
									.equals(Config.FUNCTION_REAL_OUTTIMEREPAIR)
							|| functioncode
									.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)) {// 改派、超时派单
						map.put("functionCode", Config.FUNCTION_REAL_GETMANAGERLIST);
						
						url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_GETMANAGERLIST).get(0)
										.getFunctionUrl();
						/*System.out.println("houseId---------改派>"
								+ task.getHouse_id());*/
						System.out.println("houseId---------改派>" + houseId);
					} else if (functioncode
							.equals(Config.FUNCTION_REAL_GETMANAGERDISPATCHTASKLIST)
							|| functioncode
									.equals(Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST)
							|| functioncode
									.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER)
							|| functioncode
									.equals(Config.FUNCTION_REAL_OUTTIMEREPAIROFDEPART)) {// 部门主管派单、部门主管改派，超时改派
						map.put("functionCode", Config.FUNCTION_REAL_GETSERVERLIST);
						//map.put("functionCode", Config.FUNCTION_REAL_GETMANAGERLIST);
						map.put("departDispatcherId", user.getUserId());
						url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_GETSERVERLIST).get(0)
										.getFunctionUrl();
					
						System.out.println("managerId---------部门主管派单、改派>"
								+ user.getUserId());
					} else if (functioncode.equals(Config.FUNCTION_REAL_MYAPPLY)) {
						if (peopleType.equals(Config.DEPART_DISPATCHER)) {//部门派单员
							map.put("functionCode",
									Config.FUNCTION_REAL_GETSERVERLIST);
							map.put("departDispatcherId", user.getUserId());
							
							url = Config.SERVER_URL
									+ user.getFunctionlistFromUser(
											Config.FUNCTION_REAL_GETSERVERLIST)
											.get(0).getFunctionUrl();
						} else {
							map.put("functionCode",
									Config.FUNCTION_REAL_GETMANAGERLIST);
							
							url = Config.SERVER_URL
									+ user.getFunctionlistFromUser(
											Config.FUNCTION_REAL_GETMANAGERLIST)
											.get(0).getFunctionUrl();
						}
					}
					//map.put("houseId", task.getHouse_id());
					map.put("houseId", houseId);
					String setsessionid = "";
					User user = SingleSample.getInstance(
							SingleDetailActivity.this).getUser();
					if (null != user) {
						if (null != user.getSessionId()
								&& !user.getSessionId().equals("")) {
							setsessionid = user.getSessionId();
						}
					}
					if(null != url){
						result = HttpUtil.postRequestSe(url, map, setsessionid);
						Log.e("获取服务人员的result", result);
						Log.e("有url,分配任务界面，需要获取服务人员列表","有url,分配任务界面，需要获取服务人员列表");
						if (result.contains("rows")) {
							result = result.replace("rows", "servers");
						}
						if (result.contains("departDispatcherList")) {
							result = result.replace("departDispatcherList", "servers");
						}
						message = new JSONObject(result).getString("message");
						String flag = new JSONObject(result).getString("flag");
						if(flag.equals(Config.CONNECT_SUCCESS2)){
							java.lang.reflect.Type type = new TypeToken<User>() {
							}.getType();
							Gson gson = new Gson();
							DataSupport.deleteAll(Server.class);
							u = gson.fromJson(result, type);
							servers = u.getServers();
							mHandler.obtainMessage(Config.HANDLER_MSG_GETSEVER_SUCCESS,
									message).sendToTarget();// 通知主线程数据发送成功
						}else{
							mHandler.obtainMessage(Config.HANDLER_MSG_FAIL,
									message).sendToTarget();// 通知主线程数据发送成功
						}
					}else{
						mHandler.obtainMessage(Config.HANDLER_MSG_FAIL,
								"此时不用获取服务人员信息").sendToTarget();// 通知主线程数据发送成功
						Log.e("无url,查看详情界面","无url,查看详情界面");
					}
					
				} catch (Exception e) {
					Log.e("ServiceScheduleActivity", "json数据获取报错");
					mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, "json数据获取报错")
							.sendToTarget();
					e.printStackTrace();
				}

			} else {
				mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, "请设置网络")
						.sendToTarget();

			}
		}

	/**
	 * 获取详情界面数据
	 */
	Runnable getDataRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				String url = Tool.getUrlFromUrl(user,
						initPF.getProgressFunction());
				String result = null;
				String getDetailFunctionCode = Tool
						.getDetailFunctionCode(initPF.getProgressFunction());
				Map<String, String> map = new HashMap<String, String>();
				Log.e("getdata>>functioncode", getDetailFunctionCode);
				map.put("functionCode", getDetailFunctionCode);
				map.put("repairId", task.getRepairId());
				Log.e("repairId---222", task.getRepairId());

				result = HttpUtil.postRequestSe(url, map, sessionId);
				Log.e("任务想情的result1", result);
				JSONObject jsonObj = new JSONObject(result);
				String total = jsonObj.getString("total");
				message = jsonObj.getString("message");
				String flag = jsonObj.getString("flag");
				String rows = jsonObj.getString("rows");

				if (total.equals("0")) {
					mHandler.obtainMessage(Config.HANDLER_MSG_GETTASK_FAIL,
							"该任务不存在!").sendToTarget();
				} else {
					java.lang.reflect.Type type = new TypeToken<Task>() {
					}.getType();
					Gson gson = new Gson();
					JSONArray jsonArray = new JSONArray(rows);
					JSONObject jsonObject = jsonArray.getJSONObject(0);
					task = gson.fromJson(jsonObject.toString(), type);
					Log.e("task", task.getSolvedDescript() + "");
					task = Tool.setTaskAll(initProgressFunctions,
							listRealFunctionCode, peopleType, task, user);
					isReporter = Tool.isReporter(task, user.getUserId(),
							peopleType);
					if (flag.equals(Config.CONNECT_SUCCESS2)) {
						boolean flagb = false;
						String urlstr = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_DOWNLOADREPAIRFILE)
										.get(0).getFunctionUrl();
						map.put("sessionId", sessionId);
						map.put("functionCode",
								Config.FUNCTION_REAL_DOWNLOADREPAIRFILE);
						if (StringUtil.isStringAvailable(task
								.getProblemImage1())) {
							map.put("fileName", task.getProblemImage1());
							flagb = UploadService.downFile(urlstr,
									Config.IMAGE_PATH, map);
						}
						if (StringUtil.isStringAvailable(task
								.getProblemImage2())) {
							map.put("fileName", task.getProblemImage2());
							flagb = UploadService.downFile(urlstr,
									Config.IMAGE_PATH, map);
						}
						if (StringUtil
								.isStringAvailable(task.getProblemVoice())) {
							map.put("fileName", task.getProblemVoice());
							flagb = UploadService.downFile(urlstr,
									Config.VOICE_PATH, map);
						}
						if (StringUtil
								.isStringAvailable(task.getSolvedImage1())) {
							map.put("fileName", task.getSolvedImage1());
							flagb = UploadService.downFile(urlstr,
									Config.IMAGE_PATH, map);
						}
						if (StringUtil
								.isStringAvailable(task.getSolvedImage2())) {
							map.put("fileName", task.getSolvedImage2());
							flagb = UploadService.downFile(urlstr,
									Config.IMAGE_PATH, map);
						}
						if (StringUtil.isStringAvailable(task.getSolvedVoice())) {
							map.put("fileName", task.getSolvedVoice());
							flagb = UploadService.downFile(urlstr,
									Config.VOICE_PATH, map);
						}
						if (flagb) {
							mHandler.obtainMessage(Config.HANDLER_MSG_SUCCESS,
									message).sendToTarget();// 通知主线程数据发送成功
						} else {
							mHandler.obtainMessage(Config.HANDLER_MSG_SUCCESS,
									message).sendToTarget();// 通知主线程数据发送成功

						}
					} else {

						mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
								.sendToTarget();// 通知主线程数据发送成功
					}

				}
			} catch (Exception e) {
				Log.e("ServiceScheduleActivity", "json数据获取报错");
				message = "json解析出错";
				mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
						.sendToTarget();
				e.printStackTrace();
			}

		}
	};

	/**
	 * 按钮操作与服务器交互线程
	 */
	Runnable postOperationRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub

			try {
				String result = null;
				Map<String, String> map = new HashMap<String, String>();
				Log.e(operationName + "functionCode", operationFunctionCode);
				String url = Tool.getUrlFromUrl(user, operationFunctionCode);
				Log.e(operationName + "functionCode", operationFunctionCode);
				map.put("url是",url);
				map.put("repairId", task.getRepairId());
				result = HttpUtil.postRequestSe(url, map, sessionId);
				Log.e(operationName + "result", result);
				JSONObject jsonObj = new JSONObject(result);
				message = jsonObj.getString("message");
				String flag = jsonObj.getString("flag");
				if (StringUtil.isStringEqual(operationName, "开始维修")) {
					repairTime = new JSONObject(result).getString("repairTime");
				}
				if (flag.equals(Config.CONNECT_SUCCESS2)) {
					mHandler.obtainMessage(
							Config.HANDLER_MSG_OPERATION_SUCCESS, message)
							.sendToTarget();// 通知主线程数据发送成功

				} else {
					mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
							.sendToTarget();
				}

			} catch (Exception e) {
				message = "json数据获取出错";
				mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
						.sendToTarget();

				e.printStackTrace();
			}
		}
	};

	/**
	 * 本地保存维修任务
	 */
	private void saveLocalTask() {
		if (user.isTaskExistByRepairId(task.getRepairId())) {// 存在本地保存
			Task localtask = user.getTasksByRepairId(task.getRepairId()).get(0);
			long taskid = localtask.getId();
			Task savetask = new Task();
			task.setRepairTime(repairTime);
			task.setStopflag(false);
			task.setSolvedDescript(localtask.getSolvedDescript());
			task.setSolvedImage1(localtask.getSolvedImage1());
			task.setSolvedImage2(localtask.getSolvedImage2());
			task.setSolvedVoice(localtask.getSolvedVoice());
			//task.setSolvedVoiceTime(localtask.getSolvedVoiceTime());
			savetask = task;
			savetask.setUser(user);
			savetask.save();
			user.update(user.getId());
			if (user.deleteTaskByTaskId(taskid)) {
				Log.e("开始维修", "repairId任务更新成功");
			} else {
				Log.e("开始维修", "repairId任务更新失败");
			}
		} else {// 没有本地保存
			Task savetask = new Task();
			task.setRepairTime(repairTime);
			task.setStopflag(false);
			savetask = task;
			savetask.setUser(user);
			savetask.save();
			user.update(user.getId());
		}

		functionPeopleType = Tool.getFunctionPeopleType(listRealFunctionCode,
				peopleType, isReporter);
		initTS = Tool.getInitTaskStateByCode(initPF, "serving");
	}

}
